package com.sccba.framework.web.service;

import javax.annotation.Resource;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sccba.common.utils.http.HttpClientUtils;
import com.sccba.common.utils.http.HttpUtils;
import com.sccba.common.utils.ip.AddressUtils;
import com.sccba.framework.security.context.AuthenticationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.sccba.common.constant.CacheConstants;
import com.sccba.common.constant.Constants;
import com.sccba.common.constant.UserConstants;
import com.sccba.common.core.domain.entity.SysUser;
import com.sccba.common.core.domain.model.LoginUser;
import com.sccba.common.core.redis.RedisCache;
import com.sccba.common.exception.ServiceException;
import com.sccba.common.exception.user.BlackListException;
import com.sccba.common.exception.user.CaptchaException;
import com.sccba.common.exception.user.CaptchaExpireException;
import com.sccba.common.exception.user.UserNotExistsException;
import com.sccba.common.exception.user.UserPasswordNotMatchException;
import com.sccba.common.utils.DateUtils;
import com.sccba.common.utils.MessageUtils;
import com.sccba.common.utils.StringUtils;
import com.sccba.common.utils.ip.IpUtils;
import com.sccba.framework.manager.AsyncManager;
import com.sccba.framework.manager.factory.AsyncFactory;
import com.sccba.system.service.ISysConfigService;
import com.sccba.system.service.ISysUserService;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
//            authenticationToken.setDetails("OAuth");
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
//        loginUser.setExpireTime(-1l);
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    private static final String DEFAULT_PWD = "default";

    public String oAuthLogin (String code) {
        if (StringUtils.isEmpty(code)) {
            throw new ServiceException("code值为空，登录失败，请重试！");
        }
        String accessToken = getAccessToken();
        String userId = getUserId(code, accessToken);

        // 用户验证
        Authentication authentication;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userId, DEFAULT_PWD);
            authenticationToken.setDetails("OAuth");
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userId, Constants.LOGIN_FAIL, e.getMessage()));
            throw new ServiceException(e.getMessage());
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userId, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        loginUser.setExpireTime(-1l);
        return tokenService.createToken(loginUser);
    }

    private static final String CORP_ID = "ww1ebf94a46c9b46df";
    private static final String CORP_SECRET = "j2khvKGmfUTt8WcOUTaNtFVExW9BvGhqI4szXQFxBbg";

    private static final String ACCESS_TOKEN_KEY = "access_token";

    private static final String EXPIRES_IN_KEY = "expires_in";

    public String getAccessToken () {
        String accessToken = redisCache.getCacheObject(CacheConstants.OAUTH_ACCESS_TOKEN_KEY);
        if (StringUtils.isEmpty(accessToken)) {
//            String url = "http://7.22.1.64/cgi-bin/gettoken?corpid=" + CORP_ID + "&corpsecret=" + CORP_SECRET;
//            String response = HttpUtils.sendGet(url);
            String url = "http://7.22.1.64/cgi-bin/gettoken";
            Map<String, Object> params = new HashMap<>();
            params.put("corpid", CORP_ID);
            params.put("corpsecret", CORP_SECRET);
            String response = HttpClientUtils.sendGet(url, params);
            JSONObject jsonObject;
            try {
                jsonObject = JSON.parseObject(response);
                if (null == jsonObject || StringUtils.isEmpty(accessToken = jsonObject.getString(ACCESS_TOKEN_KEY))) {
                    throw new ServiceException("获取access_token失败，清联系管理员！");
                }
            } catch (Exception ex) {
                log.error("异常信息:{}", ex.getMessage());
//                ex.printStackTrace();
                throw new ServiceException("获取access_token失败，清联系管理员！");
            }
            redisCache.setCacheObject(CacheConstants.OAUTH_ACCESS_TOKEN_KEY, accessToken, jsonObject.getInteger(EXPIRES_IN_KEY) - 5, TimeUnit.SECONDS);
        }
        return accessToken;
    }

    private static final String USER_ID_KEY = "UserId";

    private String getUserId (String code, String accessToken) {
//        String url = "http://7.22.1.64/cgi-bin/user/getuserinfo?access_token=" + accessToken + "&code=" + code;
//        String response = HttpUtils.sendGet(url);
        String url = "http://7.22.1.64/cgi-bin/user/getuserinfo";
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", accessToken);
        params.put("code", code);
        String response = HttpClientUtils.sendGet(url, params);
        String userId;
        try {
            JSONObject jsonObject = JSON.parseObject(response);
            if (null == jsonObject || StringUtils.isEmpty(userId = jsonObject.getString(USER_ID_KEY))) {
                throw new ServiceException("获取UserId失败，清联系管理员！");
            }
        } catch (Exception ex) {
            log.error("异常信息:{}", ex.getMessage());
//            ex.printStackTrace();
            throw new ServiceException("获取UserId失败，清联系管理员！");
        }
        return userId;
    }
}
